<template>
  <div class="app">
     <el-form :model="form" 
     label-width="auto" 
     style="max-width: 600px" 
     ref="formRef"
     :rules="xx"
     >
    <el-form-item label="正确密码" prop="oldPassword">
      <el-input v-model="form.oldPassword" />
    </el-form-item>
        <el-form-item label="修改密码" prop="password">
      <el-input v-model="form.password" />
    </el-form-item>
        <el-form-item label="再次输入密码" prop="password1">
      <el-input v-model="form.password1" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit(formRef)">确认修改</el-button>
    </el-form-item>
  </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router' // 引入 useRouter
//导入校验规则
import { save } from '../api/login'
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";//引入onMounted
import { mima } from "../api/login.js";//引入分类接口
import { cuser } from "../stores/user.js";//引入用户id
import { el } from 'element-plus/es/locale';

//获取用户id
const id = cuser().user.id;
// 定义表单数据
const form = ref({
  oldPassword: '',
  password: '',
  password1: '',
  id: id
  
})
const xx = ref({
  oldPassword: [
    { required: true, message: "请输入当前密码", trigger: "blur" },
    { min: 5, max: 16, message: "当前密码的长度必须为5~16位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 16, message: "密码长度必须为5~16位", trigger: "blur" },
  ],
  password1: {
    validator(rule, value, callback) {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      }
      if (value !== form.value.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
  },
});
const formRef = ref(null); //引入ref

const router = useRouter();
const yy=async()=>{
 const res= await mima(form.value)
 console.log(res);
 if(res.code==20011){
  ElMessage.success(res.msg);
  setTimeout(() => {
    router.push("/");
  }, 2000);
 }else{
  ElMessage.error(res.msg);
 }
}
//点击修改按钮
const onSubmit = (formRef) => {
 formRef.validate((valid) => {
    if (valid) {
      console.log("校验成功");
      yy();
    }else{
      console.log("校验失败");
    }
 })
}

import {cs} from "../stores/zhuangtai.js";
const zt=cs()
onMounted(()=>{
  if(zt.zhuangtai==""){
    ElMessage({
      message: "请先登录",
      type: "warning",
    });
    router.push("/")
  }
})
</script>

<style scoped>
.app{
  width: 50%;
  height: 230px;
  border: 1px solid #ccc; 
  padding: 40px;
  background-color: #fff;
  border-radius: 3px;
}
</style>